import { User } from "../model";
import express, { Request, Response } from 'express';
import jwt from 'jsonwebtoken';
import { SECRET_KEY } from "../constant";
var router = express.Router();

router.get('/', async (req: Request, res: Response) => {
  const { current = 1, pageSize = 10, name, status } = req.query;
  const data = await User.find({
    ...(name && { name }) as any,
    ...(status && { status }) as any
  })
    .skip((Number(current) - 1) * Number(pageSize)) // 跳过第current * pageSize 条数据
    .limit(Number(pageSize)); // 取出后面的 pageSize 条数据
  const total = await User.countDocuments({
    ...(name && { name }) as any,
    ...(status && { status }) as any
  });
  return res.status(200).json({ success: true, data, total });
})

router.post('/', (req: Request, res: Response) => {
  // return res.json({ success: true });
  const body = req.body;
  const UserModel = new User({ ...body });
  UserModel.save();
  return res.json({ success: true });
})

router.delete('/:id', async (req: Request, res: Response) => {
  const { id } = req.params;
  await User.findByIdAndDelete(id);
  return res.status(200).json({ success: true });
})

router.put('/:id', async (req: Request, res: Response) => {
  const { id } = req.params;
  const body = req.body;
  await User.findByIdAndUpdate({ _id: id }, body);
  return res.status(200).json({ success: true });
})

router.get('/:id', async (req: Request, res: Response) => {
  const { id } = req.params;
  const UserObj = await User.findById(id)
  if (UserObj) {
    return res.status(200).json({ success: true, data: UserObj });
  } else {
    return res.status(500).json({ success: false })
  }
});

router.post('/login', async (req: Request, res: Response) => {
  const { name, password } = req.body;
  const user = await User.findOne({ name, password });
  if (user) {
    const token = jwt.sign({ id: user._id }, SECRET_KEY, { expiresIn: '1h' });
    return res.status(200).json({ success: true, data: user, token });
  } else {
    return res.status(200).json({ success: false, data: user, message: '用户名或密码错误！' })
  }
});

export default router;
